package Meter::Action::SetupNotifications;

#===============================================================================
#     REVISION:  $Id: SetupNotifications.pm 154 2011-08-29 11:21:39Z xdr.box@gmail.com $
#  DESCRIPTION:  Setup email notifications
#===============================================================================

use strict;
use warnings;

use Readonly;
Readonly our $VERSION => qw($Revision: 154 $) [1];

use English qw( -no_match_vars );
use Email::Valid;

#use Smart::Comments;

use Meter::Log;
use Meter::Email qw(send_email);
use Meter::Utils qw(get_site_url);

use base qw(Meter::Action);

sub generate_page_content {
    my $self = shift;

    my $logger = get_logger();

    if ( $ENV{'REQUEST_METHOD'} eq 'GET' ) {
        return $self->process_template( 'setup_notifications.tt2',
            { email => $self->{'user'}->email() } );
    }

    my $username = $self->{'user'}->username();
    my $email    = $self->{'params'}{'email'};

    if ( $email ne q{} ) {
        my $normalized_email = eval {
            Email::Valid->address(
                -address => $email,
                %{ $self->{'config'}{'extra_email_validity_checks'} }
            );
        };
        ### normalized_email: $normalized_email

        if (   $EVAL_ERROR
            or not defined $normalized_email
            or $normalized_email ne $email )
        {
            ## no critic (ProhibitPackageVars)
            my $why = $EVAL_ERROR || $Email::Valid::Details || q{};

            $logger->error("Email is invalid: $why");

            return $self->redirect_error(
                'Ошибка настройки уведомлений: email указан неверно',
                'setup_notifications'
            );
        }

        my $site_url = get_site_url();

        eval {
            Meter::Email::send_email(
                to      => $email,
                subject => 'Тестовое сообщение',
                text    => <<"END_TEXT",
Это тестовое сообщение от системы учёта показаний водных счётчиков.
Если вы его читаете, значит Email-уведомления настроены правильно.
--
$site_url
END_TEXT
            );
        };

        if ($EVAL_ERROR) {
            my $why = $EVAL_ERROR;
            $logger->error("Test email failed: $why");

            return $self->redirect_error(
                'Ошибка настройки уведомлений: при отправке тестового сообщения возникли проблемы',
                'setup_notifications'
            );
        }
    }

    eval {
        $self->{'user'}->email($email);
        $self->{'user'}->update();
    };

    if ($EVAL_ERROR) {
        my $why = $EVAL_ERROR;
        $logger->error("Cannot set email for user '$username': $why");

        return $self->redirect_error(
            'Ошибка настройки уведомлений',
            'setup_notifications', $why );
    }

    $logger->info(
        "Email for user '$username' has been successfully set to '$email'");

    return $self->redirect_ok(
        'Email уведомления успешно настроены',
        'setup_notifications' );
}

sub get_error_regexes_list {
    my $self = shift;

    return [
        {   regex => qr/\Qemail fails 'regexp' constraint\E/xms,
            message =>
                'email не соответствует установленному формату',
        },
    ];
}

1;
